<?php
abstract class BLL {


    private $dao_list = null;
    private $bll_list = null;

    /**
     * 设置dao是从master上读取数据还是从slave上读取数据
     * @var boolean
     */
    public $dao_read_from_master = false;

    public $enable_cache = false;

    public function __construct() {
    }


    public function enable_dao_read_from_master ($boolean) {
        $this->dao_read_from_master = $boolean;
    }

    /**
     * @param $dao_name - string
     * @return Aifang_Core_DAO
     */
    public function get_dao ($dao_name) {
        if (!isset($this->dao_list[$dao_name])) {
            apf_require_class($dao_name);
            $this->dao_list[$dao_name] = new $dao_name();
        }
        $this->dao_list[$dao_name]->read_from_master = $this->dao_read_from_master;
        return $this->dao_list[$dao_name];
    }

    public function get_bll ($bll_name) {
        if (!isset($this->bll_list[$bll_name])) {
            apf_require_class($bll_name);
            $this->bll_list[$bll_name] = new $bll_name();
        }
        $this->bll_list[$bll_name]->dao_read_from_master = $this->dao_read_from_master;
        return $this->bll_list[$bll_name];
    }

    /**
     * muilt params instance of Aifang_Core_DAO
     * @return string
     */
    protected function get_dao_key () {
        $argv = func_get_args ();
        $key = "";
        foreach ($argv as $dao) {
            $key .= $dao->get_key("BLLKEY");
        }
        return md5($key);
    }

    final protected function build_key ($key) {
        return "BLL-KEY-" . $key;
    }

    /**
     * 格式化ID数组，去掉空的项目
     * @param array $id_array
     */
    public function format_id_array($id_array) {
        if (empty($id_array) || !is_array($id_array)) {
            return array();
        }
        foreach ($id_array as $k=>$v) {
            if (empty($v)) {
                unset($id_array[$k]);
            } else {
                $id_array[$k] = intval($v);
            }
        }
        return $id_array;
    }

    /**
     * 将ID数组格式化成例如 1,2,3
     */
    public function join_id_array ($id_array) {
        $id_array = $this->format_id_array($id_array);
        if (empty($id_array)) {
            return '';
        } else {
            return join(',',$id_array);
        }
    }

    /**
     * 将 array('id1','id2') 这样的数组变成 'id1','id2' 这样的字符串，用户sql语句
     */
    public function join_string_array ($ids,$glue="'") {
        if (empty($ids) || !is_array($ids)) {
            return '';
        } else {
            $tmp = array();
            foreach ($ids as $val) {
                $tmp[] = addslashes($val);
            }
            return "$glue".join("$glue,$glue",$tmp)."$glue";
        }
    }

    public function session_act(){
        //TODO 其他操作
        session_name('anjuke-oa');
        session_start();
    }

}